#include "Renderer_PCH.h"
#include "VertexArrayRequest.h"

/*--------------------------------------------------------------------------*/

VertexArrayRequest::VertexArrayRequest(ISurface* surface) :
	m_surface(surface)
{
	__Check(surface);
}

/*--------------------------------------------------------------------------*/

VertexArrayRequest::~VertexArrayRequest()
{

}

/*--------------------------------------------------------------------------*/

void* VertexArrayRequest::DoRequest()
{
	RVertexArray* vao = NULL;
	
	if (m_surface->GetModel())
	{
		vao = g_Renderer->GetRendererStorageMgr()->CreateVertexArray(::GetFileName(m_surface->GetModel()->GetPath()) + "_" + std::to_string(m_surface->GetId()));
	}
	else
	{
		vao = g_Renderer->GetRendererStorageMgr()->CreateVertexArray(m_surface->GetName());
	}

	uint vb = 0;

	glGenBuffers(1, &vb);
	__Check(vb);

	glBindBuffer(GL_ARRAY_BUFFER, vb);
	glBufferData(GL_ARRAY_BUFFER, m_surface->GetSize(), m_surface->GetVertexData(), GL_STATIC_DRAW);

	if (m_surface->vPosition0())
	{
		const SemanticInfo* s = g_Renderer->GetSemanticInfo(ESemantic::iPosition0);
		__Check(s);
		vao->m_declarations.push_back(RVertexDeclaration(vb, (uint)m_surface->vPosition0() - (uint)m_surface->GetVertexData(), s));
	}

	if (m_surface->vNormal0())
	{
		const SemanticInfo* s = g_Renderer->GetSemanticInfo(ESemantic::iNormal0);
		__Check(s);
		vao->m_declarations.push_back(RVertexDeclaration(vb, (uint)m_surface->vNormal0() - (uint)m_surface->GetVertexData(), s));
	}

	if (m_surface->vTexcoord0())
	{
		const SemanticInfo* s = g_Renderer->GetSemanticInfo(ESemantic::iTexcoord0);
		__Check(s);
		vao->m_declarations.push_back(RVertexDeclaration(vb, (uint)m_surface->vTexcoord0() - (uint)m_surface->GetVertexData(), s));
	}

	/*--------------------------------------------------------------------------*/

	glGenBuffers(1, &vao->m_bufferIB);
	__Check(vao->m_bufferIB);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vao->m_bufferIB);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_surface->GetNumIndices() * sizeof(ushort), m_surface->GetIndices(), GL_STATIC_DRAW);
	vao->m_numIndices = m_surface->GetNumIndices();

	__Info("[RENDERER] Vertex Array %s loaded as %p", vao->GetName().c_str(), vao);
	return vao;
}

/*--------------------------------------------------------------------------*/
